package interviewClassic150;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class IsPalindrome {
    public boolean isPalindrome(String s) {
        //新增一个List集合来存储有效字符
        List<Character> validChars = new ArrayList<>();
        for (int i = 0; i < s.length(); i++) {
            char cur = s.charAt(i);
            Character valid = extract(cur);//将当前字符提取为有效字符，如果非字母和数字则返回null
            if (valid != null) validChars.add(valid);
        }
        //接下来对集合进行操作
        if (validChars.isEmpty()) return true;//空的那么是有效的
        int left = 0;
        int right = validChars.size() - 1;
        while (left < right) {
            char leftChar = validChars.get(left);
            char rightChar = validChars.get(right);
            if (leftChar != rightChar) return false;
            left++;
            right--;
        }

        return true;
    }

    private Character extract(char cur) {
        if ((cur >= '0' && cur <= '9') || (cur >= 'a' && cur <= 'z')) return cur;
        if (cur >= 'A' && cur <= 'Z') return (char)('a' + cur - 'A');
        return null;
    }
}
